import React, { useState, useEffect } from 'react';
import {
    EditOutlined,
    DeleteOutlined,
    CloseOutlined,
    QuestionCircleOutlined,
    PlusCircleOutlined,
    LoadingOutlined,
    CheckCircleTwoTone,
    CloseCircleTwoTone
} from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-layout';
import { Layout, Form, Row, Col, Input, Radio, Checkbox, DatePicker, Button, Image, Modal, message, Tag, Spin } from 'antd';
import moment from 'moment';
import { history } from 'umi';
import { PlanItemParam, PlanTimeListParams, ProgramListParams } from './data.d';
import SetPlayTimeModel from './components/SetPlayTimeModel';
import ProgramModel from './components/ProgramModel';
import { FormInstance } from 'antd/lib/form';
import styles from './index.less';
import styles1 from '../Program/index.less';
import { programDetail } from '../Program/service';
import { repackPlan } from './service';

const { Content } = Layout;
const layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 16 },
};

const { RangePicker } = DatePicker;
const antIcon = <LoadingOutlined style={{ fontSize: 12 }} spin />;

const formRef = React.createRef<FormInstance>();
let programIds = new Array(); //节目列表 --按时段播放
let keepProgramIds = new Array(); //节目列表 --持续播放
let disabledTimeList = new Array(); //获取所有循环时间段的时间范围，用于时间控制
let status = "add";
const weekTrans = {
    Monday: "星期一",
    Tuesday: "星期二",
    Wednesday: "星期三",
    Thursday: "星期四",
    Friday: "星期五",
    Saturday: "星期六",
    Sunday: "星期日",
}

const disabledDate = (current: any) => {
    return current < moment(new Date(moment().format('YYYY/MM/DD')));
}

const CreatePlan: React.FC<{}> = (props) => {
    const [planInfo, setPlanInfo] = useState<PlanItemParam>({});
    const [defaultPlan, setDefaultPlan] = useState<boolean>(false); //默认计划
    const [timeList, handleTimeList] = useState<PlanTimeListParams[]>([]); //循环时间段列表 -- 按时段播放
    const [refresh, handleRefresh] = useState<boolean>(false); //是否刷新列表
    const [programList, handleProgramList] = useState<ProgramListParams[]>([]); //节目列表
    const [values, setValues] = useState<ProgramListParams>(); //循环项值对象
    const [publishWayDisabled, handlePublishWayDisabled] = useState<boolean>(false);
    const [planDateDisabled, handlePlanDateDisabled] = useState<boolean>(false);
    const [setPlayTimeModalVisible, handleSetPlayTimeModelVisible] = useState<boolean>(false);
    const [programModalVisible, handleProgramModelVisible] = useState<boolean>(false);
    const [deleteModalVisible, handleDeleteModalVisible] = useState<boolean>(false);
    const [index, handleIndex] = useState<number>(-1); //循环时间段列表 -- 操作项索引
    const [programSelectIndex, handleProgramSelectIndex] = useState<number>(0); //循环时间段列表 -- 选中状态
    const [programErrorIndex, handleProgramErrorIndex] = useState<number>(); //循环时间段列表【非空】 -- 选中状态
    const [typeDisabled, handleTypeDisabled] = useState<string>(""); //循环时间段列表 -- 循环周期种类【每天/每周/每月】

    const [validate, handleValidate] = useState<number>(0); //选择时间 -- 有效日期
    const [repackPlanList, setRepackPlanList] = useState<Array<any>>([]); //循环时间段列表 -- 按时段播放
    const [repackModalVisible, handleRepackModalVisible] = useState<boolean>(false);
    const [repackFinish, handleRepackFinish] = useState<boolean>(false);
    const [form] = Form.useForm();

    const repackPlanRequest = (list: Array<any>) => {
        let resList = new Array;
        function startRequest() {
            //定义counts，用来收集请求的次数，（也可以用resList的length进行判断）
            let counts = 0;
            return function requestFunc() {
                if (counts == list.length) {
                    handleRepackFinish(true);
                    localStorage.removeItem("programInfo");
                    localStorage.removeItem("planUpdate");
                    return;
                }
                let arg = list[counts].name;
                let a = new Promise((res, rej) => {
                    const id = list[counts].id;
                    repackPlan(id).then(result => {
                        if (result && result.code === 200) {
                            list[counts].status = "success";
                            res(true);
                        } else {
                            list[counts].status = "failed";
                            res(false);
                        }
                        setRepackPlanList(list.concat());

                    })
                })
                //无论成功或者失败都要进行下一次，以免阻塞，成功请求的末尾有s标志，失败的末尾有f标志
                a.then(() => {
                    counts++;
                    resList.push(arg + ' s');
                    requestFunc(list[counts])
                }).catch(err => {
                    // resList.push(arg + 'f');
                    //递归调用
                    // console.log("======递归调用==========")
                    // requestFunc(list[counts])
                    console.log(err)
                })
            }
        }
        let start = startRequest();
        start(list[0]);
    }

    useEffect(() => {
        setTimeout(function () {
            const programInfo = localStorage.getItem("programInfo");
            if (programInfo) {
                const programId = JSON.parse(programInfo)?.id;
                const planUpdate = localStorage.getItem("planUpdate");
                if (planUpdate == "true") {
                    if (programId) {
                        new Promise((resolve, reject) => {
                            programDetail(programId)
                                .then((res) => {
                                    if (res && res.code === 200) {
                                        let data = res.data;
                                        const list = data.plans;
                                        if (list && list.length > 0) {
                                            const planList = list.map(item => { return { id: item.id, name: item.name, status: 'spinning' } });
                                            if (planList.length > 0) {
                                                setRepackPlanList(planList);
                                                handleRepackModalVisible(true);
                                                repackPlanRequest(planList);
                                            }
                                        } else {
                                            localStorage.removeItem("programInfo");
                                            localStorage.removeItem("planUpdate");
                                        }
                                        resolve(true);
                                    } else {
                                        message.error('请求失败，' + res.message);
                                        resolve(false);
                                    }
                                })
                                .catch((error) => {
                                    message.error('请求失败');
                                    reject(error);
                                });
                        });
                    }
                } else {
                    localStorage.removeItem("programInfo");
                    localStorage.removeItem("planUpdate");
                }
            } else {
                localStorage.removeItem("planUpdate");
            }
        }, 500)
    }, []);

    useEffect(() => { //只在第一次加载时执行该函数
        //初始化信息
        console.log(props.location)
        if (props.location.state) {
            status = "edit";
            setPlanInfo(props.location.state);
            console.log(planInfo)
            if (planInfo?.name) {
                planInfo?.publishWay === 1 && planInfo?.publishDatetime ? handlePublishWayDisabled(true) : handlePublishWayDisabled(false);
                const playConfig = JSON.parse(planInfo?.playConfig);
                handleProgramList(playConfig[0].programList);
                if (planInfo?.playMode === 0) {//持续播放
                    handlePlanDateDisabled(true);
                    keepProgramIds = playConfig[0].programList.concat();
                    setValues(playConfig[0].programList);
                } else {//按时段播放
                    keepProgramIds = [];
                    handleTimeList(playConfig);
                    handlePlanDateDisabled(false);
                }
                setDefaultPlan(planInfo?.defaultPlan);
                formRef.current?.setFieldsValue({
                    "name": planInfo?.name,
                    "defaultPlan":planInfo?.defaultPlan,
                    "playStrategy": planInfo?.playStrategy,
                    "publishType": planInfo?.publishType,
                    "playMode": planInfo?.playMode,
                    "plan-date-picker": planInfo?.startDatetime ? [moment(planInfo?.startDatetime), moment(planInfo?.endDatetime)] : null,
                    "publishWay": planInfo?.publishWay,
                    "publishDatetimeType": planInfo?.publishDatetime ? "custom" : "default",
                    "plan-time-picker": planInfo?.publishDatetime ? moment(planInfo?.publishDatetime) : null,
                    "description": planInfo?.description,
                });
                if (planInfo?.flag) {
                    console.log("发布");
                    keepProgramIds = playConfig[0].programList.concat();
                    setValues(playConfig[0].programList);
                }
            }
        } else {
            status = "add";
            programIds = [];
            keepProgramIds = [];
        }
        let length = planInfo?.description ? planInfo?.description.length : 0;
        const showCunt = document.querySelector("textarea").parentNode;
        showCunt.setAttribute("data-count", length + " / 200");
        showCunt?.addEventListener("keyup", function () {
            length = this.querySelector("textarea").value.length;
            this.setAttribute("data-count", length + " / 200");
        });
    }, [planInfo]);

    useEffect(() => {
        if (refresh) {
            timeList[index] = JSON.parse(JSON.stringify(values));
            handleRefresh(false);
        }
    });

    useEffect(() => {
        if (!planDateDisabled) {
            if (timeList.length > 0) {
                handleProgramSelectIndex(0); //默认选中第一个
                handleProgramList(timeList[0].programList);
            } else {
                handleProgramList([]);
            }
        }
    }, [timeList]);

    //弹出【设置播放时间段】对话框
    const showSetPlayTimeModel = (e: Event, item: PlanTimeListParams, index: number) => {
        e.stopPropagation();
        //获取所有循环时间段的时间范围，用于时间控制
        disabledTimeList = [];
        for (let i in timeList) {
            if (parseInt(i) !== index) {
                const disabledTimeItem = new Object;
                for (var key in timeList[i]) {
                    if (timeList[i][key] != "programList") {
                        disabledTimeItem[key] = timeList[i][key];
                    }
                }
                disabledTimeList.push(disabledTimeItem);
            }
        }
        //根据第一个时间段控制哪个循环周期可用
        setValues(item);
        if (item) {//点击编辑
            if (timeList.length > 1) {
                handleTypeDisabled(item.type);
            } else {
                handleTypeDisabled("");
            }
        } else {//点击添加
            if (timeList.length > 0) {//前面有值时，按照第一个
                const item = timeList[0];
                handleTypeDisabled(item.type);
            } else {
                handleTypeDisabled("");
            }
        }
        handleSetPlayTimeModelVisible(true);
    }

    //设置播放时间段对话框【确定】
    const setPlayTimeModelConfirm = (values: any) => {
        handleSetPlayTimeModelVisible(false);
        let type = 'edit';
        let itemId = values.id;
        if (itemId == undefined && timeList != undefined) {
            type = "add";
            if (timeList.length > 0) {
                itemId = (timeList.length).toString();
            } else {
                itemId = "0";
            }
            values.id = itemId;
            values.programList = [];
        }
        if (type == "edit") {
            for (let i = 0; i < timeList.length; i++) {
                const item = timeList[i];
                if (item.id === itemId) {
                    handleIndex(i);
                }
            }
        } else if (type == "add") {
            handleIndex(timeList.length);
        }
        setValues(values);
        handleRefresh(true);
        if (type == "add") {
            setTimeout(function () {
                document.querySelector('.left ul li:last-child')?.click();
            }, 200);

        }
    }

    //弹出【添加节目】对话框
    const showProgramModel = (index: number) => {
        if (planDateDisabled) { //持续播放
            const values = new Object();
            values["programList"] = keepProgramIds;
            setValues(values);
        } else { //按时段播放
            if (timeList[index]) {
                setValues(timeList[index]);
            } else {
                message.warn('请先添加循环时间段！');
                return;
            }
        }
        handleProgramModelVisible(true);
    }
    //弹出【添加节目】对话框 --确认
    const programModelConfirm = (values: PlanTimeListParams) => {
        if (planDateDisabled) {//持续播放 
            keepProgramIds = values.programList;
            handleProgramModelVisible(false);
            handleProgramList(keepProgramIds);
        } else {//按时段播放
            const index = parseInt(values.id);
            timeList[index] = values;
            handleProgramModelVisible(false);
            handleTimeList(timeList);
            const array = timeList[index].programList;
            handleProgramList(array);
            handleProgramErrorIndex(-1);
        }
    }

    const handleFinish = (values: { [key: string]: any }) => { //下一步values
        console.log(values)
        if(defaultPlan && !planDateDisabled){
            message.warn('默认计划不能按时段播放');
            return;
        }
        //当发布方式：定时发布 并且 发布时间：自定义时间时
        if (values.publishDatetimeType && values.publishDatetimeType == "custom") {
            if (planInfo.publishDatetime && planInfo.endDatetime) {
                if (planInfo.publishDatetime > planInfo.endDatetime) {
                    message.warn('自定义时间要在计划日期时间段内');
                    return;
                } else {
                    const date = new Date();
                    const year = date.getFullYear();
                    const month = date.getMonth() + 1;
                    const day = date.getDate();
                    const hour = date.getHours();
                    const minutes = date.getMinutes() + 1;
                    let currentDate = year.toString() + '-' +
                        (month >= 10 ? month.toString() : "0" + month) + '-' +
                        (day >= 10 ? day.toString() : "0" + day) + " " +
                        (hour >= 10 ? hour.toString() : "0" + hour) + ":" +
                        (minutes >= 10 ? minutes.toString() : "0" + minutes) + ":00";
                    if (planInfo.publishDatetime < currentDate) {
                        message.warn('自定义时间要在当前时间之后');
                        return;
                    }
                }
            }
        }

        if (!planDateDisabled && timeList.length == 0) {
            message.warn('请至少添加一个循环时间段');
            return;
        }

        for (var key in values) {
            if (key != "plan-time-picker" && key != "plan-date-picker") {
                planInfo[key] = values[key];
            }
        }
        //提取节目列表id
        programIds = [];
        if (planDateDisabled) {//持续播放
            for (let i in keepProgramIds) {
                const programItem = keepProgramIds[i];
                programIds.push(parseInt(programItem.id));
            }
        } else { //按时段播放
            for (let i in timeList) {
                const timeItem = timeList[i];
                const programItems = timeItem.programList;
                if (programItems.length == 0) {
                    message.warn('第' + (parseInt(i) + 1) + '个循环时间段请添加关联节目');
                    handleProgramErrorIndex(i);
                    return;
                }
                for (let j in programItems) {
                    const programItem = programItems[j];
                    programIds.push(parseInt(programItem.id));
                }
            }
        }

        var newSet = new Set(programIds);
        programIds = Array.from(newSet);
        if (programIds.length == 0) {
            message.warn('请添加关联节目');
            return;
        }
        if(defaultPlan && programIds.length >1){
            message.warn('默认计划只能添加一个节目');
            return;
        }
        planInfo["programIds"] = programIds.toString();

        //发布时间 默认事件去掉publishDatetime
        if (planInfo["publishDatetimeType"] === "default") {
            planInfo["publishDatetime"] = null;
        }

        if (planDateDisabled) {//持续播放
            // planInfo["publishDatetime"] = null;
            const temp = new Object();
            const array = new Array();
            temp["programList"] = keepProgramIds;
            temp["startTime"] = "00:00:00",
                temp["endTime"] = "23:59:59",
                array.push(temp);
            planInfo["playConfig"] = JSON.stringify(array);
        } else {//按时段播放
            planInfo["playConfig"] = JSON.stringify(timeList);
            keepProgramIds = [];
        }
        console.log(planInfo)
        history.push({ pathname: '/plan/list/equipment/', state: planInfo });
    };

    const publishWayChange = (obj: any) => { //发布方式
        const value = obj.target.value;
        value === 1 ? handlePublishWayDisabled(true) : handlePublishWayDisabled(false);
        formRef.current?.setFieldsValue({ "publishWay": value })
    }

    const publishDatetimeChange = (obj: any) => { //发布时间
        const value = obj.target.value;
        formRef.current?.setFieldsValue({ "publishDatetimeType": value });
        value === "custom" ? handlePublishWayDisabled(true) : handlePublishWayDisabled(false);
    }

    const playIntervalChange = (obj: any) => { //播放模式
        const value = obj.target.value;
        if (value === 0) { //持续播放
            handlePlanDateDisabled(true);
            handleProgramList(keepProgramIds);
        } else if (value === 1) { //按时段播放
            handlePlanDateDisabled(false);
            if (timeList.length > 0) {
                if (timeList[0].programList) {//节目列表有值
                    handleProgramList(timeList[0].programList);
                    handleProgramSelectIndex(0);
                    handleProgramErrorIndex(-1);
                }
            } else {
                handleProgramList([]);
            }
        }
        formRef.current?.setFieldsValue({ "playMode": value });
    }

    const planDatePickChange = (value: any, dateString: string) => { //计划日期
        if (dateString && dateString[0] && dateString[1]) {
            planInfo["startDatetime"] = dateString[0] + " 00:00:00";
            planInfo["endDatetime"] = dateString[1] + " 23:59:59";
            formRef.current?.setFieldsValue({
                "plan-date-picker": [moment(planInfo?.startDatetime), moment(planInfo?.endDatetime)],
            });
        }
    }

    const publishTimePickChange = (date: any, dateString: string) => { //选择时间
        if (dateString) {
            planInfo["publishDatetime"] = dateString + ":00";
        }
    }

    //删除时间段--删除弹出框
    const delTimeConfirm = (e: Event, id: string) => {
        e.stopPropagation();
        Modal.confirm({
            visible: deleteModalVisible,
            title: '确定删除此时间段',
            icon: <QuestionCircleOutlined />,
            okText: '确认',
            cancelText: '取消',
            onOk: () => {
                return new Promise((resolve, reject) => {
                    let array = JSON.parse(JSON.stringify(timeList));
                    for (let i in array) {
                        let item = array[i];
                        if (item.id == id) {
                            array.splice(i, 1);
                        }
                    }
                    if (array.length > 0) {
                        array.map((item: PlanTimeListParams, index: number) => {
                            item.id = index.toString();
                        })
                    }
                    handleTimeList(array);
                    message.success('删除成功', 1);
                    handleDeleteModalVisible(false);
                    resolve(true);
                });
            },
        });
    };

    //删除节目--删除弹出框
    const delProgramConfirm = (id: string) => {
        Modal.confirm({
            visible: deleteModalVisible,
            title: '确定删除此节目？',
            icon: <QuestionCircleOutlined />,
            okText: '确认',
            cancelText: '取消',
            onOk: () => {
                if (planDateDisabled) {//持续播放
                    for (let i in keepProgramIds) {
                        let item = keepProgramIds[i];
                        if (item.id == id) {
                            keepProgramIds.splice(i, 1);
                        }
                    }
                    handleProgramList(keepProgramIds.concat());
                    // handleRefresh(true);
                } else {//按时段播放
                    let selected = timeList[programSelectIndex];
                    let array = JSON.parse(JSON.stringify(selected.programList));
                    for (let i in array) {
                        let item = array[i];
                        if (item.id == id) {
                            array.splice(i, 1);
                        }
                    }
                    timeList[programSelectIndex].programList = array;
                    handleTimeList(timeList);
                    handleProgramList(array);
                }
                handleDeleteModalVisible(false);
            },
        });
    };
    //循环时间段选中状态
    const programSelect = (item: PlanTimeListParams) => {
        handleProgramSelectIndex(parseInt(item.id));
        handleProgramList(item.programList);
    }

    const disabledHour = () => {
        var hours = [];
        if (validate == moment().date()) {
            for (var i = 0; i < moment().hour(); i++) {
                hours.push(i);
            }
        }
        return hours;
    }

    const disabledMinutes = (selectedHour) => {
        var minutes = [];
        if (validate == moment().date()) {
            if (selectedHour === moment().hour()) {
                for (var i = 0; i < moment().minute() + 1; i++) {
                    minutes.push(i);
                }
            }
        }
        return minutes;
    }

    const onDefaultPlanChange = (e:any) =>{
        form.setFieldsValue({"defaultPlan":e.target.checked});
        setDefaultPlan(e.target.checked);
    }

    return (
        <PageContainer title={status == "add" ? "新建计划" : "编辑计划"}>
            <Content
                className={styles.site_layout_background}
            >
                <h4>设置日程</h4>
                <Form {...layout} ref={formRef} form={form} scrollToFirstError onFinish={handleFinish}>
                    <Row>
                        <Col span={12}>
                            <Form.Item
                                name="name"
                                label="计划名称"
                                rules={[
                                    { required: true, max: 32, whitespace: true },
                                ]}
                            >
                                <Input placeholder="请输入计划名称" style={{ maxWidth: 200 }} />
                            </Form.Item>
                            <Form.Item
                                name="defaultPlan"
                                label="默认计划"
                                extra="默认计划只能是持续播放模式，并且只能关联一个节目"
                            >
                                <Checkbox checked={defaultPlan} onChange={onDefaultPlanChange}></Checkbox>
                            </Form.Item>
                            <Form.Item
                                name="playStrategy"
                                label="播放策略"
                                initialValue={0}
                            >
                                <Radio.Group defaultValue="0">
                                    <Radio value={0}>替换</Radio>
                                    <Radio value={1} style={{ display: "none" }}>插播模式</Radio>
                                </Radio.Group>
                            </Form.Item>
                            <Form.Item
                                name="publishType"
                                label="发布类型"
                                initialValue={0}
                            >
                                <Radio.Group defaultValue="0">
                                    <Radio value={0}>独立发布</Radio>
                                    <Radio value={1} style={{ display: "none" }}>拼接发布</Radio>
                                    <Radio value={2} style={{ display: "none" }}>同步发布</Radio>
                                </Radio.Group>
                            </Form.Item>
                            <Form.Item
                                name="playMode"
                                label="播放模式"
                                initialValue={1}
                            >
                                <Radio.Group defaultValue={1} onChange={playIntervalChange}>
                                    <Radio value={1}>按时段播放</Radio>
                                    <Radio value={0}>持续播放</Radio>
                                </Radio.Group>
                            </Form.Item>
                            {planDateDisabled == false ? (
                                <Form.Item
                                    name="plan-date-picker"
                                    label="计划日期"
                                    rules={[
                                        { type: 'array', required: true },
                                        {
                                            validator: (rule, value, callback) => {
                                                if (!value) {
                                                    callback();
                                                }
                                                const endDatetime = planInfo?.endDatetime?.split(" ")[0].replace(/-/g, "");
                                                if (endDatetime) {
                                                    const date = new Date();
                                                    const year = date.getFullYear();
                                                    const month = date.getMonth() + 1;
                                                    const day = date.getDate();
                                                    let currentDate = year.toString() + (month >= 10 ? month.toString() : "0" + month) + (day >= 10 ? day.toString() : "0" + day);
                                                    if (parseInt(endDatetime) >= parseInt(currentDate)) {
                                                        callback();
                                                    } else {
                                                        callback('计划日期截止日要在当前时间之后');
                                                    }
                                                }
                                            },
                                        }
                                    ]} >
                                    <RangePicker disabledDate={disabledDate} onChange={planDatePickChange} />
                                </Form.Item>
                            ) : null}
                        </Col>
                        <Col span={12}>
                            <Form.Item
                                name="publishWay"
                                label="发布方式"
                                initialValue={0}
                            >
                                <Radio.Group defaultValue={0} onChange={publishWayChange}>
                                    <Radio value={0}>实时发布</Radio>
                                    <Radio value={1}>定时发布</Radio>
                                </Radio.Group>
                            </Form.Item>
                            <Form.Item
                                noStyle
                                shouldUpdate={(prevValues, currentValues) =>
                                    prevValues.publishWay !== currentValues.publishWay
                                }
                            >
                                {({ getFieldValue }) => {
                                    return getFieldValue('publishWay') === 1 ? (
                                        <Form.Item name="publishDatetimeType" label="发布时间" initialValue="default">
                                            <Radio.Group onChange={publishDatetimeChange}>
                                                <Radio value="default">默认时间</Radio>
                                                <Radio value="custom">自定义时间</Radio>
                                            </Radio.Group>
                                        </Form.Item>
                                    ) : null;
                                }}
                            </Form.Item>
                            <Form.Item
                                noStyle
                                shouldUpdate={(prevValues, currentValues) =>
                                    prevValues.publishDatetimeType !== currentValues.publishDatetimeType
                                }
                            >
                                {({ getFieldValue }) => {
                                    return (publishWayDisabled && getFieldValue('publishDatetimeType') === "custom") ? (
                                        <Form.Item
                                            name="plan-time-picker"
                                            label="选择时间"
                                            rules={[{ required: true }]}
                                        >
                                            <DatePicker
                                                disabledDate={disabledDate}
                                                disabledHours={disabledHour}
                                                disabledMinutes={disabledMinutes}
                                                showTime={{
                                                    hideDisabledOptions: true,
                                                    defaultValue: moment('HH:mm'),
                                                }}
                                                showNow={false}
                                                format="YYYY-MM-DD HH:mm"
                                                onSelect={(value) => {
                                                    handleValidate(value.date());
                                                }}
                                                onChange={publishTimePickChange}
                                            />
                                        </Form.Item>
                                    ) : (null);
                                }}
                            </Form.Item>
                            <Form.Item
                                name="description"
                                label="描述"
                                rules={[{ max: 200 }]}
                                className={styles.description}
                            >
                                <Input.TextArea rows={4} style={{ resize: "none" }} placeholder="描述最多200个字" maxLength="200" />
                            </Form.Item>
                        </Col>
                        <Col span={24} className={styles.playInterval} >
                            <Form.Item noStyle>
                                {planDateDisabled == false ? (
                                    <div className="content left">
                                        <ul>
                                            {timeList.length > 0 ? (
                                                <React.Fragment>
                                                    {timeList.map((item, index) =>
                                                        <li key={index} id={item.id} className={`${programSelectIndex == item.id ? "selected" : ""} ${programErrorIndex == item.id ? "error" : ""}`} onClick={() => programSelect(item)}>
                                                            <div>
                                                                <strong>循环时间段：</strong>
                                                                <time>{item.startTime}<span style={{ margin: "0.25rem" }}>~</span>{item.endTime}</time>
                                                                <span className="control">
                                                                    <a title="编辑" onClick={(e) => showSetPlayTimeModel(e, item, index)}><EditOutlined /></a>
                                                                    <a title="删除" onClick={(e) => delTimeConfirm(e, item.id)}><DeleteOutlined /></a>
                                                                </span>
                                                            </div>
                                                            <div className="">
                                                                <strong>循环周期：</strong>
                                                                <time>
                                                                    {item.type == "day" ? (<Tag color="blue">每天</Tag>) : (
                                                                        item.type == "week" ?
                                                                            (<React.Fragment>
                                                                                <Row>
                                                                                    <Col className="label">每周：</Col>
                                                                                    <Col className="list">
                                                                                        {item.week.map((w: string, i: number) =>
                                                                                            <Tag key={i} color="blue">
                                                                                                {weekTrans[w]}
                                                                                            </Tag>
                                                                                        )}
                                                                                    </Col>
                                                                                </Row>

                                                                            </React.Fragment>) : (
                                                                                item.type == "month" ? (
                                                                                    <React.Fragment>
                                                                                        <Row>
                                                                                            <Col className="label">每月：</Col>
                                                                                            <Col className="list">
                                                                                                {item.month.map((m: string, j: number) =>
                                                                                                    <Tag key={j} color="blue">
                                                                                                        {m}号
                                                                                                    </Tag>
                                                                                                )}
                                                                                            </Col>
                                                                                        </Row>
                                                                                    </React.Fragment>
                                                                                ) : ("")
                                                                            )
                                                                    )}
                                                                </time>
                                                            </div>
                                                        </li>
                                                    )
                                                    }
                                                </React.Fragment>
                                            ) : ("")}
                                        </ul>
                                        <div className="add" onClick={(e) => showSetPlayTimeModel(e, "", "")}>
                                            <span>
                                                <PlusCircleOutlined style={{ fontSize: '20px', verticalAlign: 'text-bottom', marginRight: 5 }} />
                                                <span>添加时间段</span>
                                            </span>
                                        </div>
                                    </div>
                                ) : null}
                                <div className="content right scroll">
                                    <ul>
                                        {programList && programList.length > 0 ? (
                                            <React.Fragment>
                                                {programList.map((item, index) =>
                                                    <li key={index}>
                                                        <Image src={item.previewImgUrl} preview={false} />
                                                        <div className="mask">
                                                            <span className="name" title={item.name}>{item.name}</span>
                                                            <p>
                                                                <span>{item.resolution}</span>
                                                                <span>{item.totalTime}秒</span>
                                                            </p>
                                                            <a className="close" title="删除" onClick={() => delProgramConfirm(item.id)} ><CloseOutlined /></a>
                                                        </div>
                                                    </li>
                                                )}
                                            </React.Fragment>
                                        ) : ("")}
                                        <li>
                                            <div className="add1" onClick={() => showProgramModel(programSelectIndex)} >
                                                <span className="button">
                                                    <PlusCircleOutlined style={{ fontSize: 32 }} />
                                                    <span style={{ display: 'block', marginTop: 5, fontSize: 16 }}>添加节目</span>
                                                </span>
                                            </div>
                                        </li>
                                    </ul>
                                </div>
                            </Form.Item>
                        </Col>
                        <Col span={24} className={styles.footer}>
                            <Form.Item noStyle>
                                <Button style={{ marginRight: 50 }} onClick={() => history.push('/plan/list/')}>取消</Button>
                                <Button type="primary" htmlType="submit">下一步</Button>
                            </Form.Item>
                        </Col>
                    </Row>
                </Form>
            </Content>
            <SetPlayTimeModel
                values={values}
                typeDisabled={typeDisabled}
                disabledTimeList={disabledTimeList}
                onSubmit={(values) => setPlayTimeModelConfirm(values)}
                onCancel={() => handleSetPlayTimeModelVisible(false)}
                modalVisible={setPlayTimeModalVisible}
            ></SetPlayTimeModel>
            <ProgramModel
                values={values}
                playMode={planDateDisabled}
                onSubmit={(values) => programModelConfirm(values)}
                onCancel={() => handleProgramModelVisible(false)}
                modalVisible={programModalVisible}
            ></ProgramModel>
            <Modal
                title="更新计划"
                visible={repackModalVisible}
                footer={repackFinish ? <Button onClick={() => handleRepackModalVisible(false)}>关闭</Button> : null}
                closable={false}
                className={styles1.RepackPlanModel}
            >
                {repackPlanList.map(item => {
                    return item.status == 'spinning' ? (
                        <p key={item.id}>计划 {item.name} 更新中，请稍后...<Spin indicator={antIcon} style={{ marginLeft: 10 }} /></p>
                    ) : (
                        item.status == 'success' ? (
                            <p key={item.id}>计划 {item.name} 更新完成<CheckCircleTwoTone twoToneColor="#52c41a" style={{ marginLeft: 10 }} /></p>
                        ) : (
                            <p key={item.id}>计划 {item.name} 更新失败<CloseCircleTwoTone twoToneColor="#ff4d4f" style={{ marginLeft: 10 }} /></p>
                        )
                    )
                }
                )}
            </Modal>

        </PageContainer>
    );
};

export default CreatePlan;